var router = require('express').Router();
var util = require('util');
var async = require('async');

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var Message = require('../models/Message');
var User = require('../models/User');

//添加交流
router.post('/add', function(req, res) {
	var message = req.body;
	if (!message.media || !message.content || !message.to)
		return res.send(resultJson(3));

	message.from = message._user._id;
	message.create = new Date();
	message.categroy = 0;
	new Message(message).save(function(err, msg) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		var item = JSON.parse(JSON.stringify(msg));
    
		User.findOne({
			_id: item.from
		}, {
			_id: 1,
			name: 1,
			photo: 1
		}).exec(function(err, user) {
			if (err)
				res.send(resultJson(0));
			if (!user)
				user = {};
            var fromUser = user;

            User.findOne({
                _id: item.to
            }, {
                _id: 1,
                name: 1,
                phone:1,
                category:1,
                photo: 1
            }).exec(function(err, user) {
                if (err)
                    res.send(resultJson(0));
                var tomes = user.category == 30 ? '您的好友 '+fromUser.name+' 给你发来消息！':'your friend-'+fromUser.name+' sent a message!';
                var obj ={};
                obj.platform = [2];
                obj.alias = user.phone;
                obj.alertmsg = tomes;
                obj.contentmsg = 'test';
                var pus = new Object();
                pus.user = fromUser;
                pus.type = 1;
                obj.option = {"extra":pus};
                Utils.pushMessage(obj); 

                item.userName = fromUser.name;
                item.userPhoto = fromUser.photo;
                res.send(resultJson(0, item));

                
            });
		});
	})
});


//删除
router.post('/remove', function(req, res) {
    var chat = req.body;
    var fid =chat.fid;
    var uid =chat.uid;
    Message.remove({
           $or: [{
            from: fid,
            to: uid
        }, {
            from: uid,
            to: fid
        }],
    }, function(err) {
        if (err) {
            logger.error(err);
            res.send(resultJson(2));
        } else
            res.send(resultJson(0));
    });
});

//接收前台输入的发送信息
router.post('/sdm', function(req, res) {
    var user = req.body;
    var cid = user.cid;
    var fid =user.fid;
    var con =user.cont;

    user.from = cid;
    user.to = fid;
    user.content = con;
    user.categroy = 1;
    user.create = new Date();
    Message.find(
           {
           from:cid,
           to:fid,
           categroy:1
           },function(err,message) {
               if (err) {
                  return res.send(resultJson(2));
               }
               if(message.length == 0){
                   console.log("1");
                   new Message(user).save(function(err, msg) {
                        if (err) {
                            logger.error(err);
                            return res.send(resultJson(2));
                        }
                
                        User.findOne({
                            _id: cid
                        }, {
                            _id: 1,
                            name: 1,
                            photo: 1
                        }).exec(function(err, user) {
                            if (err)
                                res.send(resultJson(2));
                            var fromUser = user;
                            User.findOne({
                                _id: fid
                            }, {
                                _id: 1,
                                name: 1,
                                phone:1,
                                category:1,
                                photo: 1
                            }).exec(function(err, user) {
                                if (err)
                                    res.send(resultJson(2));
                                var tomes = user.category == 30 ? fromUser.name+' 请求加您为好友!':fromUser.name+' request you to add as your friend.';
                                var obj ={};
                                obj.platform = [2];
                                obj.alias = user.phone;
                                obj.alertmsg = tomes;
                                obj.contentmsg = 'test';
                                var pus = new Object();
                                pus.user = fromUser;
                                pus.type = 2;
                                obj.option = {"extra":pus};
                                Utils.pushMessage(obj); 
                
                                res.send(resultJson(0));
                
                            });
                        });
                    });
               }
               res.send(resultJson(0));
          });
    
    
});

//接收前台输入的发送信息
router.post('/send', function(req, res) {
    var user = req.body;
    var cid = user.cid;
    var fid =user.fid;
    var con =user.cont;

    user.from = cid;
    user.to = fid;
    user.content = con;
    user.categroy = 1;
    user.create = new Date();
    Message.find(
           {
           from:cid,
           to:fid,
           categroy:1
           },function(err,message) {
               if (err) {
                  return res.send(resultJson(2));
               }
               if(message.length == 0){
                   console.log("1");
                   new Message(user).save(function(err, msg) {
                        if (err) {
                            logger.error(err);
                            return res.send(resultJson(2));
                        }
                
                        User.findOne({
                            _id: cid
                        }, {
                            _id: 1,
                            name: 1,
                            photo: 1
                        }).exec(function(err, user) {
                            if (err)
                                res.send(resultJson(2));
                            var fromUser = user;
                            User.findOne({
                                _id: fid
                            }, {
                                _id: 1,
                                name: 1,
                                phone:1,
                                category:1,
                                photo: 1
                            }).exec(function(err, user) {
                                if (err)
                                    res.send(resultJson(2));
                                var tomes = user.category == 30 ? fromUser.name+' 请求加您为好友!':fromUser.name+' request you to add as your friend.';
                                var obj ={};
                                obj.platform = [2];
                                obj.alias = user.phone;
                                obj.alertmsg = tomes;
                                obj.contentmsg = 'test';
                                var pus = new Object();
                                pus.user = fromUser;
                                pus.type = 2;
                                obj.option = {"extra":pus};
                                Utils.pushMessage(obj); 
                
                                res.send(resultJson(0));
                
                            });
                        });
                    });
               }
               res.send(resultJson(0));
          });
    
    
});

//判断接收的消息及验证
router.post('/friendmessage', function(req, res) {
   var user = req.body;
       var userId = user._id;
       Message.find(
           {
           to:userId,
           categroy:1
           },function(err,message) {
            if (err){
                return res.send(resultJson(200));
            }else{
                var userArrs = new Array();
                var count = 0;
                for(var i=0;i<message.length;i++){
                       var userId = message[i].from;
                        var cont = message[i].content;
                        
                        User.findOne({_id:userId}, function(err, user) {
                            if (!err) {
                                 ++count;
                                 var userCon = new Object();
                                 userCon.user = user;
                                 userCon.content = cont;
                                 userArrs.push(userCon);
                                  if(count==message.length){
                                  return res.send(resultJson(0,JSON.parse(JSON.stringify(userArrs))));
                                }
                            
                            }else{
                                return res.send(resultJson(2)); 
                            }
                        
                
                        });//end find
                    

                }//end for
            }
        });
      
       
});


router.post('/detail', function(req, res) {
    var from = req.body.from;
    var to = req.body.to;
    if (!from || !to)
        return res.send(resultJson(3));

    var query = Message.find({
        $or: [{
            from: from,
            to: to,
            categroy : 0
        }, {
            from: to,
            to: from,
            categroy : 0
        }],
    });
    query.sort({
        create: 1
    });
    query.exec(function(err, msgs) {
        if (err)
            return res.send(resultJson(2));

        res.send(resultJson(0, msgs));
    });
})

router.post('/list', function(req, res) {
    var user = req.body;
    var from = user._id;
	var length = user.friends && user.friends.length || 0;
    if(length == 0)
        return res.send(resultJson(0));

    var results = new Array();
    listFriendCb(res, 0, from,user.friends, results);
});


function listFriendCb(res, index, from, friends, results) {
    if (index == friends.length) {
        sendFriendCb(res, from, 0, results);
        return;
    }

    Message.findOne({
        $or: [{
            from: from,
            to: friends[index].id
        }, {
            to: from,
            from: friends[index].id
        }],
    }).sort({
        create: -1
    }).exec(function(err, message) {
        if (!err) {
            if(message) 
                results.push(message);

            index++;
            listFriendCb(res, index, from, friends, results);
        } else
            res.send(resultJson(2));
    });
}

function sendFriendCb(res, from, index, results) {
    if (index == results.length)
        return res.send(resultJson(0, results));

    var friendId = results[index].from;
    if (from == friendId)
        friendId = results[index].to;

    User.findOne({
        _id: friendId
    }, function(err, user) {
        if (!user) {
            res.send(resultJson(2));
            return;
        }
        results[index] = JSON.parse(JSON.stringify(results[index]));
        results[index].name = user.name;
        results[index].photo = user.photo;
        results[index].category = user.category;
        results[index].sex = user.sex;
        index++;
        sendFriendCb(res, from, index, results);
    });
}
module.exports = router;